package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.mapper.WmUserMapper;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.model.wemedia.dto.WmLoginDto;
import com.zhentao.model.wemedia.pojo.WmUser;
import com.zhentao.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/*
 *云计算
 *魏子纹
 *2025/6/11
 */
@Service
public class WmUserService implements com.zhentao.service.WmUserService {
    @Autowired
    private WmUserMapper wmUserMapper;

    @Override
    public ResponseResult login(WmLoginDto dto) {
        if(StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,  "用户名或密码为空");
        }

        // 根据账户查询用户是否存在
        WmUser wmUser = wmUserMapper.selectOne(new QueryWrapper<WmUser>().eq("name", dto.getName()));
        if (wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
        }

        // 校验密码
        String salt = wmUser.getSalt();
        String pwd = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
        if (pwd.equals(wmUser.getPassword())){
            // 登录成功
            // 获取token
            String token = AppJwtUtil.getToken(wmUser.getId().longValue());
            //校验
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            wmUser.setPassword(null);
            wmUser.setSalt(null);
            map.put("user", wmUser);

            return ResponseResult.okResult(map);

        }
        return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");

    }
}
